package com.example.lc.myjurisdictiondemo;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends Activity implements EasyPermissions.PermissionCallbacks {
    private String TAG = "lc";
    public static final int All_PERMISSION = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            initPermission();
        }
//        boolean jurisdictionOK = new Util(this).isJurisdictionOK();
//        if (jurisdictionOK){
//            Log.e(TAG, "if成功");
//        }else{
//            Log.e(TAG, "if失败");
//        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 将结果转发到EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        // 某些权限已被授予
        Log.e(TAG, "成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        // 某些权限被拒绝
        Log.e(TAG, "失败");
        //（可选）检查用户是否拒绝任何权限，并检查“不要再询问”。
        // 这将显示一个对话框，指示他们在应用设置中启用权限。
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle("需要权限").setRationale("某些权限没有授予,继续运行可能会崩溃.").build().show();
        }
    }

    @AfterPermissionGranted(All_PERMISSION)
    private void initPermission(){
        //shouldShoowRequestPermissionRationale,在第一次申请权限时会返回false，意味着第一次不需要告知用户申请该权限的理由，
        //如果第一次申请被拒
        String[] perms = {Manifest.permission.CAMERA};

        // 检查应用程序已经具有所需的权限
        if (EasyPermissions.hasPermissions(this, perms)) {// 有了
            Log.e(TAG, "有了相应的权限了.");
        } else {// 还没
            EasyPermissions.requestPermissions(this, "需要获取应用的相关权限",
                    All_PERMISSION, perms);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            // 做一些事情后，用户从应用程序设置界面返回
            // initPermission();
        }
    }
}
